package ai.george.quickstart.controller;


import ai.george.quickstart.advisor.CustomMessageChatMemoryAdvisor;
import com.alibaba.cloud.ai.dashscope.api.DashScopeApi;
import com.alibaba.cloud.ai.dashscope.chat.DashScopeChatOptions;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.function.Consumer;


@Tag(name = "记忆会话(自定义实现)")
@RestController
@RequestMapping("/chat-memory-custom")
public class CustomChatMemoryController {

    private final ChatClient memoryChatClient;



    /**
     * 使用构造器注入ChatClient
     *
     * @param chatClientBuilder 由starter自动创建
     */
    public CustomChatMemoryController(ChatClient.Builder chatClientBuilder) {
        //公共的chatOptions
        DashScopeChatOptions chatOptions = DashScopeChatOptions.builder()
                .withModel(DashScopeApi.ChatModel.QWEN_PLUS.getValue())
                .withTopP(0.7)
                .build();

        /**
         * 创建一个 ChatClient（没有配置默认的Advisor）
         */
        this.memoryChatClient = chatClientBuilder
                // 设置 ChatClient 中 ChatModel 的 Options 参数
                .defaultOptions(chatOptions)
                .build();
        System.out.println("CustomChatMemoryController初始化");
    }



    @Operation(summary = "ChatMemory", description = "使用自定义的Advisor实现会话记忆")
    @GetMapping("/custom-advisor")
    public String chatMemory(@RequestParam(value = "sessionId") @Parameter(name = "sessionId", description = "会话的唯一id") String sessionId,
                             @RequestParam(value = "query") @Parameter(name = "query", description = "请求内容") String query) {
        String content = memoryChatClient
                .prompt()
                .advisors(new Consumer<ChatClient.AdvisorSpec>() {
                    @Override
                    public void accept(ChatClient.AdvisorSpec advisorSpec) {
                        //可以设置Advisor上下文参数(在后续的Advisor实现类中可以使用)
                        advisorSpec.param("sessionId", sessionId);
                    }
                })
                .advisors(new CustomMessageChatMemoryAdvisor())
                .user(query)
                .call()
                .content();
        return content;
    }



}
